package com.jiashn.minio.utils;

import jdk.nashorn.internal.ir.debug.ClassHistogramElement;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author: jiangjs
 * @description: 用于文件内容加密
 * @date: 2023/10/20 11:11
 **/
@Slf4j
public class Md5Util {
    /**
     * 字符串加密
     * @param str 字符串
     * @return 加密的md5
     * @throws NoSuchAlgorithmException 异常
     */
    public static String encryptString(String str) throws NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        byte[] digest = messageDigest.digest(str.getBytes(StandardCharsets.UTF_8));
        return encryptFileBytes(digest);
    }

    /**
     * 文件直接MD5加密
     * @param file 文件
     * @return 返回加密后的md5
     */
    public static String encryptFileContent(MultipartFile file) {
        try (InputStream ism = file.getInputStream()){
            return DigestUtils.md5DigestAsHex(ism);
        }catch (Exception e){
            log.error("文件转md5报错："+e.getMessage());
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 通过流的方式加密文件
     * @param ism 流
     * @return 返回加密后的md5
     * @throws NoSuchAlgorithmException 异常
     * @throws IOException 异常
     */
    public static String encryptFileStream(InputStream ism) throws NoSuchAlgorithmException, IOException {
        byte[] bytes = new byte[1024];
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        int length = 0;
        while ((length = ism.read(bytes)) != -1){
            md5.update(bytes,0,length);
        }
        return encryptFileBytes(bytes);
    }

    /**
     * 通过字节进行加密
     * @param bytes 字节
     * @return 加密后的md5
     */
    private static String encryptFileBytes(byte[] bytes){
        StringBuilder builder = new StringBuilder();
        for (byte b : bytes) {
            if (Integer.toHexString(0xFF & b).length() == 1) {
                builder.append("0").append(Integer.toHexString(0xFF & b));
            } else {
                builder.append(Integer.toHexString(0xFF & b));
            }
        }
        return String.valueOf(builder);
    }
}
